/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lcw.library.imagepicker.ability;

import com.lcw.library.imagepicker.ResourceTable;
import com.lcw.library.imagepicker.adapter.ImagePreViewItemProvider;
import com.lcw.library.imagepicker.data.MediaFile;
import com.lcw.library.imagepicker.manager.ConfigManager;
import com.lcw.library.imagepicker.manager.SelectionManager;
import com.lcw.library.imagepicker.utils.DataUtil;
import com.lcw.library.imagepicker.utils.ResUtil;
import com.lcw.library.imagepicker.utils.Utils;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.global.configuration.Configuration;
import ohos.utils.net.Uri;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class ImagePreAbility extends BaseAbility {
    static final String IMAGE_POSITION = "imagePosition";
    private List<MediaFile> mMediaFileList;
    private int mPosition = 0;

    private Text mTvTitle;
    private Text mTvCommit;
    private Image mIvPlay;
    private PageSlider mViewPager;
    private DirectionalLayout mLlPreSelect;
    private Image mIvPreCheck;
    private ImagePreViewItemProvider mImagePreViewAdapter;
    private static final int RESULT_OK = -1;
    private DependentLayout mPageView;

    @Override
    protected int bindLayout() {
        return ResourceTable.Layout_ability_pre_image;
    }

    @Override
    protected void initView() {
        mTvTitle = (Text) findComponentById(ResourceTable.Id_tv_actionBar_title);
        mTvCommit = (Text) findComponentById(ResourceTable.Id_tv_actionBar_commit);
        mIvPlay = (Image) findComponentById(ResourceTable.Id_iv_main_play);
        mPageView = (DependentLayout) findComponentById(ResourceTable.Id_layout_pageView);
        mViewPager = (PageSlider) findComponentById(ResourceTable.Id_slider);
        mLlPreSelect = (DirectionalLayout) findComponentById(ResourceTable.Id_ll_pre_select);
        mIvPreCheck = (Image) findComponentById(ResourceTable.Id_iv_item_check);
        mViewPager.setOrientation(Component.HORIZONTAL);
        mViewPager.setSlidingPossible(true);
        int orientation = this.getResourceManager().getConfiguration().direction;
        if (orientation == Configuration.DIRECTION_HORIZONTAL) {
            mPageView.setMarginTop(10);
            mViewPager.setWidth(500);
            mViewPager.setHeight(610);
        }
    }

    @Override
    protected void initListener() {
        findComponentById(ResourceTable.Id_iv_actionBar_back).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                terminateAbility();
            }
        });

        mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageChosen(int position) {
                mTvTitle.setText(String.format("%d/%d", position + 1, mMediaFileList.size()));
                setIvPlayShow(mMediaFileList.get(position));
                updateSelectButton(mMediaFileList.get(position).getPath());
            }

            @Override
            public void onPageSlideStateChanged(int i) {
            }
        });

        mLlPreSelect.setClickedListener(v -> {
            if (ConfigManager.getInstance().isSingleType()) {
                ArrayList<String> selectPathList = SelectionManager.getInstance().getSelectPaths();
                if (!selectPathList.isEmpty()) {
                    if (!SelectionManager.isCanAddSelectionPaths
                            (mMediaFileList.get(mViewPager.getCurrentPage()).getPath(), selectPathList.get(0))) {
                        Utils.showToast(ImagePreAbility.this, ResUtil.getString(ImagePreAbility.this
                                , ResourceTable.String_single_type_choose));
                        return;
                    }
                }
            }

            boolean addSuccess = SelectionManager.getInstance().addImageToSelectList
                    (mMediaFileList.get(mViewPager.getCurrentPage()).getPath());
            if (addSuccess) {
                updateSelectButton(mMediaFileList.get(mViewPager.getCurrentPage()).getPath());
                updateCommitButton();
            } else {
                Utils.showToast(ImagePreAbility.this, ResUtil.getString(ImagePreAbility.this
                        , ResourceTable.String_select_image_max));
            }
        });

        mTvCommit.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                setResult(RESULT_OK, new Intent());
                terminateAbility();
            }
        });

        mIvPlay.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                Uri uri = Uri.getUriFromFile(new File(mMediaFileList.get(mViewPager.getCurrentPage()).getPath()));
                Operation operationBuilder = new Intent.OperationBuilder()
                        .withUri(uri)
                        .build();
                Intent intent = new Intent();
                intent.setUriAndType(uri, "video/*");
                intent.setOperation(operationBuilder);
                startAbility(intent);
            }
        });
    }

    @Override
    protected void getData() {
        mMediaFileList = DataUtil.getInstance().getMediaData();
        mPosition = getIntent().getIntParam(IMAGE_POSITION, 0);
        mTvTitle.setText(String.format("%d/%d", mPosition + 1, mMediaFileList.size()));
        mImagePreViewAdapter = new ImagePreViewItemProvider(this, mMediaFileList);
        mViewPager.setProvider(mImagePreViewAdapter);
        mViewPager.setCurrentPage(mPosition);
        setIvPlayShow(mMediaFileList.get(mPosition));
        updateSelectButton(mMediaFileList.get(mPosition).getPath());
        updateCommitButton();
    }

    private void updateCommitButton() {
        int maxCount = SelectionManager.getInstance().getMaxCount();
        int selectCount = SelectionManager.getInstance().getSelectPaths().size();
        if (selectCount == 0) {
            mTvCommit.setEnabled(false);
            mTvCommit.setText(ResUtil.getString(ImagePreAbility.this
                    , ResourceTable.String_confirm));
            return;
        }
        if (selectCount < maxCount) {
            mTvCommit.setEnabled(true);
            mTvCommit.setText(String.format(ResUtil.getString(ImagePreAbility.this
                    , ResourceTable.String_confirm_msg), selectCount, maxCount));
            return;
        }
        if (selectCount == maxCount) {
            mTvCommit.setEnabled(true);
            mTvCommit.setText(String.format(ResUtil.getString(ImagePreAbility.this
                    , ResourceTable.String_confirm), selectCount, maxCount));
        }
    }

    /**
     * 更新选择按钮状态
     *
     * @param imagePath
     */
    private void updateSelectButton(String imagePath) {
        boolean isSelect = SelectionManager.getInstance().isImageSelect(imagePath);
        Optional<PixelMapElement> element;
        if (isSelect) {
            element = ResUtil.getElementByResId(this, ResourceTable.Media_icon_image_checked);
            element.ifPresent(pixelMapElement -> mIvPreCheck.setImageElement(pixelMapElement));
        } else {
            element = ResUtil.getElementByResId(this, ResourceTable.Media_icon_image_check);
            element.ifPresent(pixelMapElement -> mIvPreCheck.setImageElement(pixelMapElement));
        }
    }

    /**
     * 设置是否显示视频播放按钮
     *
     * @param mediaFile
     */
    private void setIvPlayShow(MediaFile mediaFile) {
        if (mediaFile.getDuration() > 0) {
            mIvPlay.setVisibility(Component.VISIBLE);
        } else {
            mIvPlay.setVisibility(Component.HIDE);
        }
    }
}
